#include <Windows.h>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    SECURITY_ATTRIBUTES saAttr;
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = TRUE;
    saAttr.lpSecurityDescriptor = NULL;

    HANDLE hReadPipe, hWritePipe;
    if (!CreatePipe(&hReadPipe, &hWritePipe, &saAttr, 0))
    {
        cout << "Failed to create pipe." << endl;
        return 1;
    }

    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(STARTUPINFO));
    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
    si.cb = sizeof(STARTUPINFO);
    si.hStdOutput = hWritePipe; // 将管道的写入端作为子进程的标准输出
    si.dwFlags |= STARTF_USESTDHANDLES;

    string command = "E:/Project/Repositories/cpp/cpp/httpserver/dist/py/dist/pppppp_MinGW@13.2.0_min.exe";
    if (!CreateProcess(NULL, const_cast<char*>(command.c_str()), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi))
    {
        cout << "Failed to create process." << endl;
        return 1;
    }

    CloseHandle(hWritePipe); // 关闭写入端，因为我们只需从管道的读取端读取输出

    char buffer[4096];
    DWORD bytesRead;
    string output;
    while (true)
    {
        if (!ReadFile(hReadPipe, buffer, sizeof(buffer), &bytesRead, NULL))
            break;

        output += string(buffer, bytesRead);
        
        cout << output; // 打印输出消息

        if (output.find("12345") != string::npos)
            break;

        output.clear();
    }

    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);

    return 0;
}